///数据库初始化
let DatabaseInstance = (function() {
    let instance;
    function createInstance() {
        //// 引入 sqlite3 并设置为 verbose 模式，以便能够看到更详细的日志
        const sqlite3 = require('sqlite3').verbose();
        let db = new sqlite3.Database('/Users/baijinhao/www/testvUE/DD/src/assets/yitiji.db', (err) => {
            if (err) {
                console.error('Error opening database', err);
            } else {
                console.log('Database opened successfully');
                // 在这里，您可以执行数据库初始化操作，例如创建表
                db.run("CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT)");
    
            }
        });
        return db;
    }
    return {
        getInstance: function() {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

exports.db = DatabaseInstance.getInstance();

exports.insertAsync = async function (arg) {
    await exports.db.run('INSERT INTO data (value,key) VALUES (?,?)',arg.value,arg.key);
   // console.log('insert success');
    return 'insert success';
}

exports.query = async function (arg){
    return new Promise((resolve, reject) => {
        exports.db.all("SELECT * FROM data where key='"+arg+"'", [], (err, rows) => {
            if (err) {
                console.error('Error running query', err);
                reject(err);
            } else {
                //console.log('query success');
                //console.log('query success'+JSON.stringify(rows));
                resolve(rows);
            }
        });
    });
}  

exports.update = async function (arg){
    return new Promise((resolve, reject) => {
        exports.db.all("update data set value = ? where key = ? ", [arg.value,arg.key], (err, rows) => {
            if (err) {
               // console.error('Error running update', err);
                reject(err);
            } else {
              //  console.log('update success');
                resolve("update success");
            }
        });
    });
}  


exports.dbClose = function (){
    exports.db.close((err) => {
        if (err) {
            console.error('Error closing database', err);
        } else {
            console.log('Database closed successfully');
        }
    });
}



